<template>
    <el-row class="contain-box">
        <site-nav>&emsp;>&emsp;<strong><i>{{departmentName}}</i></strong></site-nav>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="$router.go(-1)"><i class="el-icon-arrow-left el-icon--left"/>返回
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button :disabled="duties.length === 0" :loading="submitting" @click="save" type="primary">
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-table :data="duties" @selection-change="handleSelectionChange" border ref="table" size="small">
                    <el-table-column type="selection" width="55"/>
                    <el-table-column align="center" label="职位ID" prop="dutyId" width="150"/>
                    <el-table-column align="center" label="职位名称" prop="dutyName"/>
                    <el-table-column align="center" label="说明" prop="remark"/>
                </el-table>
            </el-row>
        </div>
    </el-row>
</template>

<script lang="ts">
  import {ID} from '@/api/http';
  import DepartmentApi from '@/api/user/departmentApi';
  import DutyApi from '@/api/user/dutyApi';
  import Duty from '@/structure/duty';
  import {ElTable} from 'element-ui/types/table';
  import {Component, Vue} from 'vue-property-decorator';

  @Component
  export default class Page extends Vue {
    public submitting: boolean = false;
    public departmentId!: ID;
    public departmentName: string = '';
    public duties: Duty[] = [];
    public selected: Duty[] = [];

    public created(): void {
      this.departmentId = this.$route.params.departmentId;
      this.departmentName = this.$route.query.departmentName as string;

      DutyApi.all().then((res) => {
        this.duties = res.filter((item) => !this.$isSystemDuty(item.dutyId));
        this.getDataList();
      });
    }

    public handleSelectionChange(value: Duty[]): void {
      this.selected = value;
    }

    public getDataList(): void {
      DepartmentApi.getDistribution(this.departmentId).then((res) => {
        this.duties.forEach((position) => {
          (this.$refs.table as ElTable).toggleRowSelection(position, res.includes(position.dutyId));
        });
      });
    }

    public save(): void {
      if (this.submitting) {
        return;
      }

      this.submitting = true;

      DepartmentApi.setDistribution(this.departmentId, this.selected.map((i) => i.dutyId)).then(() => {
        this.getDataList();
        this.submitting = false;
        this.$message.success('保存成功');
      }).catch(() => {
        this.submitting = false;
      });
    }
  }
</script>

